<template>
  <el-dialog :title="state.title" v-model="visible" :close-on-click-modal="false" @opened="openFun" draggable>
    <el-form :model="state.dictForm" :rules="state.rules" ref="dictRef" label-width="80px">
      <el-form-item label="字典名称" prop="dictName">
        <el-input v-model="state.dictForm.dictName" placeholder="请输入字典名称"></el-input>
      </el-form-item>
      <el-form-item label="字典编码" prop="dictCode">
        <el-input v-model="state.dictForm.dictCode" placeholder="请输入字典编码"></el-input>
      </el-form-item>
      <el-form-item label="字典状态" prop="enabled">
        <el-switch v-model="state.dictForm.enabled" inline-prompt active-text="启用" inactive-text="停用"/>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="state.dictForm.description" type="textarea" placeholder="请输入描述"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="resetForm(dictRef)">重置</el-button>
      <el-button type="primary" :loading="isLoading" @click="submitDict">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {editDict} from "../../api/dict/sysDict";
import {errorMsg, successMsg} from "../../utils/message";
import {resetForm} from "../../utils/common";
import {computed, reactive, ref} from "vue";

const props = defineProps({
  dialogVisible: {
    type: Boolean,
    required: true,
    default: false
  },
  dictObj: Object
})

const emit = defineEmits(['update:dialogVisible', 'get-list'])

const visible = computed({
  get: () => props.dialogVisible,
  set: (val) => emit('update:dialogVisible', val)
})

const isLoading = ref(false)

const dictRef = ref()

const state = reactive({
  title: '新增',
  dictForm: {
    dictId: null,
    dictName: '',
    dictCode: '',
    description: '',
    enabled: true
  },
  rules: {
    dictName: [{required: true, message: '字典名称不能为空', trigger: 'blur'}],
    dictCode: [{required: true, message: '字典编码不能为空', trigger: 'blur'}]
  }
})

const openFun = () => {
  resetForm(dictRef.value)
  state.title = '新增'
  isLoading.value = false
  if (props.dictObj.dictId){
    state.title = '编辑'
    state.dictForm = props.dictObj
    state.dictForm.enabled = props.dictObj.enabled == 1?true:false
  }
}
//  提交
const submitDict = () => {
  dictRef.value.validate((valid) => {
    if (valid){
      isLoading.value = true
      state.dictForm.enabled = state.dictForm.enabled ? 1:0
      editDict(state.dictForm).then(res => {
        if (res.code == 200){
          successMsg(res.message)
          visible.value = false
          emit('get-list')
        } else {
          errorMsg(res.message)
        }
        isLoading.value = false
      })
    }
  })
}
</script>

<style scoped>
 :deep(.vue-treeselect__control){
  height: 30px;
}
 :deep(.el-form-item__content){
   line-height: 30px;
   font-size: 12px;
 }
</style>